package servlet;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SubmitFormServlet
 */
@WebServlet(name = "SubmitFormServlet1", urlPatterns = { "/SubmitFormServlet1" })
public class SubmitFormServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SubmitFormServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 表单参数校验
        String username = request.getParameter("username");
        String email = request.getParameter("email");

        if (username == null || username.isEmpty()) {
            request.setAttribute("error", "用户名不能为空");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        if (email == null || !email.matches("\\w+@\\w+\\.\\w+")) {
            request.setAttribute("error", "邮箱格式不正确");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        // 放行请求
        chain.doFilter(request, response);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
